%% prepare
clear all;

%% parameters
rootdir = ['..' filesep '191015_GeraldDoreenBob_Bats1'];
sampleNames = {};

%% preamble
if rootdir(end) ~= filesep
    rootdir(end+1) = filesep;
end
if isempty(sampleNames)
    listDir = dir(rootdir);
    sampleNames = cell(length(listDir)-2,1);
    for k = 3:length(listDir)
        if exist([rootdir listDir(k).name filesep 'Online' filesep],'dir')
            sampleNames{k-2} = listDir(k).name;
        end
    end
    sampleNames = sampleNames(~cellfun('isempty',sampleNames));
end

%% choose samples
fprintf('Index\tName\n');
mask = true(1,length(sampleNames));
for k = 1:length(sampleNames)
    fprintf('%d\t%s\n',k,sampleNames{k});
end
idx = input('Choose samples: ');
if not(isempty(idx))
    sampleNames = sampleNames(idx);
end

%% extract cell traces
for idxSampleName = 1:length(sampleNames)
sampleName = sampleNames{idxSampleName};
filedir = [rootdir sampleName filesep 'Online' filesep];
[measNums,frameNums] = funcFindMeas(filedir);

fprintf('%s:\n',sampleName);

for measNumN = 1:length(measNums)
measNum = measNums(measNumN);

%% load video
fileAvi = dir([filedir sprintf('M%i_*imaq.avi', measNum)]);
try
    vr = VideoReader([filedir fileAvi.name]);
    numFrames = get(vr,'NumberOfFrames');
    frame = read(vr,1);
catch
    fprintf('\tM%i is corrupted\n',measNum)
end

clear fileAvi;

end
end

return
%% functions
function [measNums,frameNums] = funcFindMeas(fileDir)
fileList = dir([fileDir 'M*_camera.ini']);
measNums  = NaN(1,length(fileList));
frameNums = NaN(1,length(fileList));
strKeyFrame = 'Frame Rate = ';
for idxFile = 1:length(fileList)
    fid = fopen([fileDir fileList(idxFile).name],'r');
    frameNums(idxFile) = getFrame(fid, strKeyFrame);
    idx1 = strfind(fileList(idxFile).name, 'M');
    idx2 = strfind(fileList(idxFile).name, '_');
    measNums(idxFile) = str2double(fileList(idxFile).name(idx1(1)+1:idx2(1)-1));
    fclose(fid);
end
end

function frame = getFrame(fid, strKeyFrame)
while ~feof(fid)
    strLine = fgets(fid);
    index = strfind(strLine, strKeyFrame);
    if ~isempty(index)
        frame = str2double(strLine(index + length(strKeyFrame):end));
        return;
    end
end
end

